package vip.manda.framework.web.http;

import vip.manda.framework.log.Log;
import vip.manda.framework.log.LogFactory;
import vip.manda.framework.util.Requester;
import vip.manda.framework.web.Method;
import vip.manda.framework.web.WebFunction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hongda.li 2022-04-14 09:53
 */
public class PathAndMethodFilter implements Filter {

    private static final Log log = LogFactory.getLog();

    @Override
    public Integer getOrder() {
        return 0;
    }

    @Override
    public boolean doFilter(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestUri = Requester.getUri(request.getRequestURI());
        String requestMethod = request.getMethod();
        Method[] methodType = WebFunction.getApiMethodType(requestUri);
        if (methodType != null) {
            for (Method method : methodType) {
                if (method.getValue().equalsIgnoreCase(requestMethod)) {
                    log.info("Capture a request[{}][{}]", requestUri, requestMethod);
                    return true;
                }
            }
            log.debug("Request method don't match[{}][{}]", requestUri, requestMethod);
            response.sendError(405, "405 error : Request method don't match!");
            return false;
        }
        log.debug("Request path don't match[{}]", requestUri);
        response.sendError(404, "404 error : Request mapping don't match!");
        return false;
    }
}
